package com.ask.forMe.langchain4j.rag.word;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.FileInputStream;
import java.util.List;

/**
 * Word转换工具1
 */
public class WordProcessor {
    /**
     * 将word标题(含样式)转换为Markdown风格
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public static String convertWordToMarkdownText(String filePath) throws Exception {
        StringBuilder markdownText = new StringBuilder();

        try (XWPFDocument document = new XWPFDocument(new FileInputStream(filePath))) {
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                int headingLevel = getHeadingLevel(paragraph);
                String text = paragraph.getText().trim();

                if (headingLevel > 0) {  // 是标题
                    // 生成Markdown风格标题 (# ## ### 等)
                    StringBuilder prefix = new StringBuilder();
                    for (int i = 0; i < headingLevel; i++) {
                        prefix.append("#");
                    }
                    markdownText.append("\n").append(prefix).append(" ").append(text).append("\n");
                } else {  // 普通段落
                    markdownText.append(text).append("\n\n");
                }
            }
        }
        return markdownText.toString();
    }

    /**
     * 获取word标题层级
     *
     * @param paragraph
     * @return
     */
    private static int getHeadingLevel(XWPFParagraph paragraph) {
        // 方法1: 通过样式名称判断
        String styleName = paragraph.getStyle();
        if (styleName != null && styleName.startsWith("Heading")) {
            try {
                return Integer.parseInt(styleName.substring("Heading".length()));
            } catch (NumberFormatException e) {
            }
        }

        // 方法2: 通过大纲级别判断
        if (paragraph.getCTP().getPPr() != null &&
                paragraph.getCTP().getPPr().getOutlineLvl() != null) {
            return paragraph.getCTP().getPPr().getOutlineLvl().getVal().intValue() + 1;
        }

        return 0;  // 不是标题
    }

    /**
     * 提取Word文档的大纲
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public List<String> extractDocumentMap(String filePath) throws Exception {
        return null;
    }
}
